package com.lcn.comm.framework.thread;

import com.lcn.comm.constant.Constants;
import com.weibo.api.motan.util.LoggerUtil;

import java.util.concurrent.TimeUnit;

/**
 * <p>类说明</p>
 *
 * @author 张峰 zfvip_it@163.com
 * @create: 2017－12－23 上午9:37
 */
public abstract class HookRunnable implements Runnable {

    /**
     * 标记是否执行结束
     */
    private volatile boolean hasOver;


    public void run() {
        Thread thread = new Thread() {
            @Override
            public void run() {
                Constants.hasExit = true;
                while (!hasOver) {//存在未结束的业务，继续等待
                    try {
                        TimeUnit.MILLISECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        //判断jvm是否退出
        if (!Constants.hasExit) {
            //未退出，将线程加入jvm钩子
            Runtime.getRuntime().addShutdownHook(thread);
        } else {
            LoggerUtil.error("jvm 已退出");
        }

        try {
            run0();
        } finally {
            hasOver = true;
            if (!thread.isAlive()) {
                //业务正常结束，将线程守护线程重jvm中移除
                Runtime.getRuntime().removeShutdownHook(thread);
            }
        }
    }


    public abstract void run0();
}
